package com.ygl.eurekaclientorder.api.controller;

import com.netflix.appinfo.InstanceInfo;
import com.spring4all.swagger.EnableSwagger2Doc;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ygl
 * @create 2019-01-16
 * @DESCRIPTION
 *
 **/
@RestController
public class OrderController {
    /**
     * springboot web组件提供
     * 默认整合ribbon负载均衡器
     * rest方式底层采用httpclient
     */
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getOrder")
    public String getOrder(){
        String object = restTemplate.getForObject("http://localhost:8082/getMember", String.class);
        System.out.println("订单服务调用会员服务得到的结果："+object);
        return object;
    }

    /**
     * restTemplate通过别名调用需要依赖ribbon
     * @return
     */
    @GetMapping("/getOrder1")
    public String getOrder1(){
        String url = "http://client-member/getMember";
        String object = restTemplate.getForObject(url, String.class);
        System.out.println("订单服务调用会员服务得到的结果："+object);
        return object;
    }

    /**
     * 探究负载均衡的原理
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/getInstances")
    public List<String> instances(){
        List<String> uris = new ArrayList<>();
        List<ServiceInstance> instances = getInstances();
        for (ServiceInstance instance : instances) {
            URI uri = instance.getUri();
            uris.add(uri.toString());
        }
        return uris;
    }

    public List<ServiceInstance>  getInstances(){
        List<ServiceInstance> instances = discoveryClient.getInstances("client-member");
        return instances;
    }
}
